<template>
  <div class="bg-white rounded-xl overflow-hidden shadow-md hover:shadow-lg transition-all">
    <div class="relative">
      <img :src="work.cover" :alt="work.title" class="w-full h-48 object-cover">
      <span 
        :class="work.status === 'completed' ? 'bg-green-500' : 'bg-yellow-500'"
        class="absolute top-2 right-2 px-2 py-1 text-xs text-white rounded"
      >
        {{ work.status === 'completed' ? '已完成' : '草稿' }}
      </span>
    </div>
    <div class="p-4">
      <div class="flex justify-between items-start mb-2">
        <h3 class="font-bold text-lg">{{ work.title }}</h3>
      </div>
      <div class="flex justify-between text-sm text-gray-500 mb-4">
        <span>创建于 {{ work.created }}</span>
        <span>{{ work.style }}风格</span>
      </div>
      <div class="flex gap-2">
        <button 
          class="flex-1 py-2 bg-primary text-white rounded hover:bg-primary/90 transition-colors text-sm"
          @click="$router.push(`/work/${work.id}/view`)"
        >
          <i class="fa fa-eye mr-1"></i> 查看
        </button>
        <button 
          class="flex-1 py-2 border border-red-300 text-red-500 rounded hover:bg-red-50 transition-colors text-sm"
          @click="handleDelete"
        >
          <i class="fa fa-trash mr-1"></i> 删除
        </button>
      </div>
    </div>
  </div>
</template>

<script setup>
// 正确的导入方式 - 直接导入默认模块
import api from '../utils/api.js'

// 使用别名调用delete方法，避免使用保留关键字
const deleteApi = api.delete

const props = defineProps({
  work: Object
})

const emit = defineEmits(['workDeleted'])

// 处理删除操作
const handleDelete = async () => {
  // 显示确认对话框
  if (confirm('确定要删除这个作品吗？此操作无法撤销。')) {
    try {
      // 获取正确的ID - 使用数据中的Id字段（后端需要的删除标识）
      // 注意：MyWorks.vue中已经将Id转换为字符串，这里直接使用即可
      const deleteId = props.work.Id
      
      // 调用删除API，使用params传递ID，api.js中会确保将其作为字符串处理
      await deleteApi('/generate/delete', {
        params: { id: deleteId }
      })
      
      // 显示成功消息
      alert('作品删除成功！')
      
      // 触发事件通知父组件（MyWorks.vue）刷新列表
      emit('workDeleted', deleteId)
    } catch (error) {
      console.error('删除作品失败:', error)
      alert('删除失败，请稍后重试')
    }
  }
}
</script>